﻿using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhAppSvc = Microsoft.Phone.Shell.PhoneApplicationService;
namespace XamlMvp
{
    public partial class MvpApplicationServiceBase
    {
        IPhoneApplicationService phoneApplicationService;
        internal IPhoneApplicationService PhoneApplicationService
        {
            get
            {
                if (phoneApplicationService == null)
                {
                    phoneApplicationService = new PhoneApplicationServiceWrapper(PhAppSvc.Current);
                }
                return phoneApplicationService;
            }
            set
            {
                phoneApplicationService = value;
            }
        }

        partial void ChainServices()
        {
            PhoneApplicationService.Activated += ApplicationActivated;
            PhoneApplicationService.Launching += ApplicationLaunching;
            PhoneApplicationService.Closing += ApplicationClosing;
            PhoneApplicationService.Deactivated += ApplicationDeactivated;

            InitializeUriMapper();
        }

        protected virtual void InitializeUriMapper() {}
        
        void ApplicationDeactivated(object sender, DeactivatedEventArgs e)
        {
            DeHydrate(new PresenterContext(PhoneApplicationService.State, true));
        }

        void ApplicationClosing(object sender, ClosingEventArgs e)
        {
            ShutDown(new PresenterContext(PhoneApplicationService.State, false));
        }

        void ApplicationLaunching(object sender, LaunchingEventArgs e)
        {
            Binders.Presenters.Context = new PresenterContext(PhoneApplicationService.State, false);
            StartUp(Binders.Presenters.Context);
        }

        void ApplicationActivated(object sender, ActivatedEventArgs e)
        {
#if MANGO
            Binders.Presenters.Context = new PresenterContext(PhoneApplicationService.State, true, e.IsApplicationInstancePreserved);
#else
            Binders.Presenters.Context = new PresenterContext(PhoneApplicationService.State, true, false);
#endif

            ReHydrate(Binders.Presenters.Context);
        }

        protected virtual void StartUp(IPresenterContext context) { }

        protected virtual void DeHydrate(IPresenterContext context) { }

        protected virtual void ReHydrate(IPresenterContext context) { }

        protected virtual void ShutDown(IPresenterContext context) { }

        partial void UnChainServices()
        {
            PhoneApplicationService.Activated -= ApplicationActivated;
            PhoneApplicationService.Launching -= ApplicationLaunching;
            PhoneApplicationService.Closing -= ApplicationClosing;
            PhoneApplicationService.Deactivated -= ApplicationDeactivated;
        }
    }
}
